﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Drawing;           //系统绘图,Font
using System.Drawing.Imaging;   //ImageFormat
using System.Drawing.Drawing2D; //LinearGradientBrush


public partial class 验证码 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.checkImg(CreatCheckNum()); //随机生成验证码 及图片
    }

    private string CreatCheckNum()
    {//随机生成验证码
        int num;
        char tmp;
        string str = string.Empty;
        System.Random Rnd = new Random();

        for (int i = 0; i < 6; i++)
        {
            num = Rnd.Next(35);
            if(num < 10) tmp = (char)('0' + num);
            else if(num%3==0) tmp = (char)('A' + num-10);
            else tmp = (char)('a' + num - 10);

            str += tmp.ToString();
        }

        Session["checkNum"] = str;  //保存验证字符串到Session 以备验证码的验证
        return str;
    }

    private void checkImg(string str)
    {//生成验证码图片
        if (str == null || str.Trim() == String.Empty) return;

        System.Drawing.Bitmap img1 = new Bitmap((int)Math.Ceiling(str.Length * 12.5), 22);
        Graphics gra = Graphics.FromImage(img1);

        try
        {
            Random rnd = new Random();  //随机数
            gra.Clear(Color.White);     //清空背景色

            //在图片上 随机画线
            for (int i = 0; i < 25; i++)
            {
                int x1 = rnd.Next(img1.Width);
                int x2 = rnd.Next(img1.Width);
                int y1 = rnd.Next(img1.Height);
                int y2 = rnd.Next(img1.Height);

                gra.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
            }

            Font font1 = new Font("Arial", 12, FontStyle.Bold);//设置字体
            //图刷
            LinearGradientBrush brush1 = new LinearGradientBrush(new Rectangle(0, 0, img1.Width, img1.Height), Color.Blue, Color.DarkBlue, 1.2f, true);
            gra.DrawString(str, font1, brush1, 2, 2);         //绘制str验证码图片

            //在图片上 绘制100个随机点
            for (int i = 0; i < 100; i++)
            {
                img1.SetPixel(rnd.Next(img1.Width), rnd.Next(img1.Height), Color.FromArgb(rnd.Next()));
            }

            //绘制 图片边框线
            gra.DrawRectangle(new Pen(Color.Silver), 0, 0, img1.Width - 1, img1.Height - 1);

            System.IO.MemoryStream ms1 = new System.IO.MemoryStream(); //创建支持存储区的内存流
            img1.Save(ms1, ImageFormat.Gif);                            //保存图片

            Response.ClearContent();//清空缓冲区
            Response.ContentType = "img1/Gif";
            Response.BinaryWrite(ms1.ToArray()); //将流内容写入字节数组
        }
        finally
        {
            gra.Dispose();  //释放gra
            img1.Dispose();
        }
    }
}
